package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerXunJianComponent;
import com.example.administrator.printoutindemo.di.module.XunJianModule;
import com.example.administrator.printoutindemo.mvp.contract.XunJianContract;
import com.example.administrator.printoutindemo.mvp.presenter.XunJianPresenter;
import com.example.administrator.printoutindemo.mvp.ui.entity.InspectionMaterialAndroid;
import com.example.administrator.printoutindemo.mvp.ui.entity.XunJian;
import com.example.administrator.printoutindemo.utils.GlideUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.activity.NanJingLu_ScanQRCodeActivity;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_ACTIVITY_XUN_JIAN)
public class XunJianActivity extends BaseActivity<XunJianPresenter> implements XunJianContract.View {


    public LocationClient mLocationClient = null;
    @BindView(R.id.img_scan)
    ImageView imgScan;
    @BindView(R.id.rb_equipment_normal)
    RadioButton rbEquipmentNormal;
    @BindView(R.id.rb_equipment_abnormal)
    RadioButton rbEquipmentAbnormal;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.xet_des)
    XEditText xetDes;
    @BindView(R.id.img)
    ImageView imgPaiZhao;
    @BindView(R.id.tv_he_dui_xu_hao)
    TextView tvHeDuiXuHao;
    @BindView(R.id.tv_dang_qian_di_zhi)
    TextView tvDangQianDiZhi;
    private double mLatitude = 0;
    private double mLongitude = 0;
    private MyLocationListener myListener = new MyLocationListener();
    private String scan_result;
    private String isQuestion = "是";
    private String imgStr = "";
    private BottomDialogUtil mBottomDialogUtilShare;

    /**
     * 将object对象转成json格式字符串
     */
    public static String toJson(Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerXunJianComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .xunJianModule(new XunJianModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_xun_jian; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_xun_jian));
        //getXunJianData();
        PhotoUtil.init(this, new FrescoIniter());

        initBaiDuLocation();
    }

    private void initBaiDuLocation() {
        //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
        //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(60000);
//        option.setScanSpan(60000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true


        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        mLocationClient.start();
        //mLocationClient为第二步初始化过的LocationClient对象
        //调用LocationClient的start()方法，便可发起定位请求
    }

    @Override
    public void getXunJianDataSuccess(XunJian entityData) {


    }

    private void getXunJianData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getXunJianData(map);
    }

    @OnClick({R.id.img_scan, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_scan:
                toScan();
                break;
            case R.id.btn_submit:
                try {
                    if (TextUtils.isEmpty(scan_result)) {
                        showMessage("请先扫描二维码");
                        toScan();
                        return;
                    }
                    if (TextUtils.isEmpty(getDes())) {
                        showMessage("请输入描述");
                        return;
                    }

                    if (rbEquipmentNormal.isChecked()) {
                        isQuestion = "是";
                    }

                    if (rbEquipmentAbnormal.isChecked()) {
                        isQuestion = "否";
                    }
                    if (TextUtils.isEmpty(imgStr)) {
                        showMessage("请拍照");
                        return;
                    }
                    InspectionMaterialAndroid inspectionMaterialAndroid = new InspectionMaterialAndroid();
                    String uid = mSharedPreferencesHelper.getString(BaseConstants.UID);
                    inspectionMaterialAndroid.setInspection_id(Integer.parseInt(uid));
                    inspectionMaterialAndroid.setSubmituid(Integer.parseInt(uid));
                    inspectionMaterialAndroid.setOut_storage_detail_id(scan_result);
                    inspectionMaterialAndroid.setSubmitquestion(getDes());
                    inspectionMaterialAndroid.setSubmittime("");
                    inspectionMaterialAndroid.setCheckuid(Integer.parseInt(uid));
                    inspectionMaterialAndroid.setDealuid(Integer.parseInt(uid));
                    inspectionMaterialAndroid.setDealstatus(0);
                    inspectionMaterialAndroid.setDealresult("");
                    inspectionMaterialAndroid.setDealtime("");
                    inspectionMaterialAndroid.setUsemoney("0");
                    inspectionMaterialAndroid.setIsQuestion(isQuestion);
                    String json = toJson(inspectionMaterialAndroid);
                    LogUtils.debugEInfo("json=" + json);
                    insertSubmitQuestionPic(json, imgStr, mLatitude, mLongitude);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void toScan() {
        Intent newIntent = new Intent(this, NanJingLu_ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    @NotNull
    private String getDes() {
        return xetDes.getText().toString().trim();
    }

    private void insertSubmitQuestionPic(String modelJson, String img, double lat, double lng) {

        showLoading();
        String methodName = "InsertSubmitQuestionPic";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("modelJson", modelJson);
        params.put("img", img);
        params.put("lat", String.valueOf(lat));
        params.put("lng", String.valueOf(lng));


        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        if (Integer.parseInt(result) == 1) {
                            showMessage("提交成功");
                            scan_result = "";
                            tvHeDuiXuHao.setText("已扫描的核对序号：");
                            imgStr = "";
                            xetDes.setText("");
                            GlideUtil.loadImage(getContext(), R.drawable.icon_add, imgPaiZhao);
                        } else {
                            showMessage("提交失败");
                        }

                    } else {
                        showMessage("提交失败");
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                scan_result = extras.getString("scan_result");
                tvHeDuiXuHao.setText("已扫描的核对序号：" + scan_result);
            }

        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }

    }

    @OnClick(R.id.img)
    public void onViewClicked() {
        xiuGaiTouXiang();
    }

    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(com.xiaoxing.zhinenghuacangku_nanjinglu.R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(XunJianActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {

                                    imgStr = ArmsUtils.bitmapToString(compressedPath);

                                    GlideUtil.loadImage(getContext(), compressedPath, imgPaiZhao);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = com.xiaoxing.zhinenghuacangku_nanjinglu.R.color.public_black;
                PhotoUtil.titleBarColor = com.xiaoxing.zhinenghuacangku_nanjinglu.R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(XunJianActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    imgStr = ArmsUtils.bitmapToString(compressedPath);
                                    GlideUtil.loadImage(getContext(), compressedPath, imgPaiZhao);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(XunJianActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f
                mLatitude = latitude;
                mLongitude = longitude;
                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明

                LogUtils.debugEInfo("onReceiveLocation==" + location.getAddrStr() + "   经纬度==" + "lat=" + latitude + " lon" + longitude);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + latitude + " lon" + longitude);
            }//此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                // 离线定位成功
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                mLatitude = lat;
                mLongitude = lon;
                LogUtils.debugEInfo("baidu_location_result", "offline location success");
                LogUtils.debugEInfo("经纬度==lat=" + lat + " lon" + lon);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeGpsLocation) {
                // GPS定位成功
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                mLatitude = lat;
                mLongitude = lon;
                LogUtils.debugEInfo("baidu_location_result", "Gps location success");
                LogUtils.debugEInfo("经纬度==lat=" + lat + " lon" + lon);
                tvDangQianDiZhi.setText(location.getAddrStr() + "   经纬度==" + "lat=" + lat + " lon" + lon);

            } else if (location.getLocType() == BDLocation.TypeOffLineLocationFail) {
                // 离线定位失败
                showMessage("GPS信号弱,定位失败,请到空旷的位置重新定位。");
                LogUtils.debugEInfo("baidu_location_result", "offline location fail");
                LogUtils.debugEInfo("GPS信号弱,定位失败,请到空旷的位置重新定位。");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocationNetworkFail) {
                // 离线定位失败
                showMessage("网络信号弱,定位失败,请检查网络状态。");
                LogUtils.debugEInfo("baidu_location_result", "Network location fail");
                LogUtils.debugEInfo("网络信号弱,定位失败,请检查网络状态。");
            } else {
//                showMessage("location type = " + location.getLocType());
                LogUtils.debugEInfo("baidu_location_result", "location type = " + location.getLocType());
                LogUtils.debugEInfo("location type = " + location.getLocType());
            }

        }
    }
}
